from statsmodels.graphics.tsaplots import plot_acf as ACF #自相关图
from statsmodels.graphics.tsaplots import plot_pacf as PACF   #偏自相关图
from statsmodels.tsa.stattools import adfuller as ADF  #平稳性检测
import pandas as pd
import tushare as ts
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
sns.set(color_codes=True)

#一、获取数据
df = ts.get_k_data('688981', start='2022-04-13', end='2024-04-13')
df.to_excel('中芯国际股价数据.xlsx', index=False)
df.set_index('date', inplace=True)
'''
#二、收盘价序列及一阶二阶差分
dataset = pd.DataFrame()
dataset['close'] = df['close']
dataset['closeDiff_1'] = df['close'].diff(1)
# 首先对一阶差分结果进行一次差分，即二阶差分
dataset['closeDiff_2'] = dataset['closeDiff_1'].diff(1)

#print(dataset)
dataset.plot(subplots=True, figsize=(18,12))
#plt.show()

#三、定阶：ACF及PACF图形
#fig = ACF(data,lags = 20)
#plt.show()
#fig = PACF(data,lags = 20)
#AR使用PACF定阶，MA使用ACF定阶，通常会找到第一个不在置信区间内的偏自相关系数
#plt.show()

#四、平稳性检验
data2 = dataset['close']
data2Diff = data2.diff()

#temp = np.array(data2)
#原收盘价序列非平稳
temp = np.array(data2Diff)[1:]
#经1次差分后的收盘价序列平稳
t = ADF(temp)  # ADF检验
print("p-value: ", t[1])
#output=pd.DataFrame(index=['Test Statistic Value', "p-value", "Lags Used", "Number of Observations Used","Critical Value(1%)","Critical Value(5%)","Critical Value(10%)"],columns=['value'])
#output['value']['Test Statistic Value'] = t[0]
#output['value']['p-value'] = t[1]
#output['value']['Lags Used'] = t[2]
#output['value']['Number of Observations Used'] = t[3]
#output['value']['Critical Value(1%)'] = t[4]['1%']
#output['value']['Critical Value(5%)'] = t[4]['5%']
#output['value']['Critical Value(10%)'] = t[4]['10%']
#print(output)

#五、白噪声检验（先用模型拟合得到残差，再对残差进行检验）
#from statsmodels.stats.diagnostic import acorr_ljungbox

# 假设你有一个时间序列模型，其残差存储在residuals变量中
# 你需要指定滞后阶数lags
# 返回的结果是一个包含检验统计量和对应的p值的元组
#test_statistic, p_value = acorr_ljungbox(residuals, lags=10)

# 输出检验统计量和对应的p值
#print("Ljung-Box test statistic:", test_statistic)
#print("p-value:", p_value)
'''
